﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMenuBar>
#include <QToolBar>
#include <QStatusBar>
#include <QLabel>
#include "centreview.h"
#include "diagramscene.h"
#include "mainwindow.h"
#include <QButtonGroup>
#include <QDebug>
#include <QFileDialog>
#include <QStandardItemModel>
#include <QStandardPaths>
#include <QToolButton>
#include "single.h"
#include "stepbase.h"
#include "relation.h"
#include <QFile>
#include "workflowxml.h"
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    initWindow();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::initWindow()
{
    initMenuBar();
    initToolBar();
    initStatusBar();

    this->setWindowIcon(QIcon(":/images/app.png"));
    this->setWindowTitle("CFD科学计算建模软件");

    QWidget* lTitleBar = ui->dockLeft->titleBarWidget();
    QWidget* lEmptyWidget = new QWidget();
    ui->dockLeft->setTitleBarWidget(lEmptyWidget);
    delete lTitleBar;

    lTitleBar = ui->dockRight->titleBarWidget();
    QWidget* lEmptyWidget2 = new QWidget();
    ui->dockRight->setTitleBarWidget(lEmptyWidget2);
    delete lTitleBar;

    lTitleBar = ui->dockButtom->titleBarWidget();
    QWidget* lEmptyWidget3 = new QWidget();
    ui->dockButtom->setTitleBarWidget(lEmptyWidget3);
    delete lTitleBar;

    contreView = new CentreView(this);
    contreView->setCacheMode(QGraphicsView::CacheBackground);
    //contreView->setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate);
    contreView->setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
    setCentralWidget(contreView);

    connect(ui->widLeft,&LeftView::WorkFlowChange,this,[=](const QModelIndex &index)
    {
        currentScene = index.data(Qt::UserRole+1).value<DiagramScene*>();
        contreView->setScene(currentScene);
    });
    connect(ui->widLeft,&LeftView::WorkFlowNameChange,this,[=](const QModelIndex &index)
    {
        currentScene->getWorkFlow()->getProperty()->name = index.data().toString();
    });
}

void MainWindow::initToolBar()
{
    //工具栏
    QToolBar *pToolBar = new QToolBar(this);
    pToolBar->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
    this->addToolBar(pToolBar);

    //创建工具栏动作
    pointerButton = new QToolButton;
    pointerButton->setCheckable(true);
    pointerButton->setChecked(true);
    pointerButton->setIcon(QPixmap(":/images/toolbar/selectop.png"));
    pointerButton->setToolTip("选择");
    linePointerButton = new QToolButton;
    linePointerButton->setCheckable(true);
    linePointerButton->setIcon(QPixmap(":/images/toolbar/lineop.png"));
    linePointerButton->setToolTip("连接");
    pointerTypeGroup = new QButtonGroup(this);
    pointerTypeGroup->addButton(pointerButton, int(MoveItem));
    pointerTypeGroup->addButton(linePointerButton, int(InsertLine));
    connect(pointerTypeGroup, QOverload<int>::of(&QButtonGroup::buttonClicked),
            this, &MainWindow::pointerGroupClicked);

    QAction *pDeleteItemAction = new QAction(QIcon(":/images/toolbar/deleteitem.png"), "删除", this);
    connect(pDeleteItemAction, &QAction::triggered, this, &MainWindow::delectStepTriggered);

    QAction *pCopyAction = new QAction(QIcon(":/images/toolbar/copy.png"), "复制", this);
    //connect(pCopyAction, SIGNAL(triggered()), m_pMainWidget, SIGNAL(sigCopyItem()));

    QAction *pPasteAction = new QAction(QIcon(":/images/toolbar/paste.png"), "粘贴", this);
    //connect(pPasteAction, SIGNAL(triggered()), m_pMainWidget, SIGNAL(sigPasteItem()));

    QAction *pCreateWFlowAction = new QAction(QIcon(":/images/toolbar/createwflow.png"), "创建工作流", this);
    //connect(pCreateWFlowAction, SIGNAL(triggered()), m_pMainWidget, SIGNAL(sigCreateWFlow()));

    QAction *pCheckAction = new QAction(QIcon(":/images/toolbar/check.png"), "校验工作流", this);
    //connect(pCheckAction, SIGNAL(triggered()), m_pMainWidget, SIGNAL(sigCheckWFlow()));

    QAction *pExecAction = new QAction(QIcon(":/images/toolbar/execwflow.png"), "执行工作流", this);
    //connect(pExecAction, SIGNAL(triggered()), m_pMainWidget, SIGNAL(sigExecWFlow()));

    QAction *pViewResultAction = new QAction(QIcon(":/images/toolbar/viewreport.png"), "查看执行结果", this);
    //connect(pViewResultAction, SIGNAL(triggered()), m_pMainWidget, SIGNAL(sigViewResult()));

    QAction *pAddComponentGroupAction = new QAction(QIcon(":/images/toolbar/addgroup.png"), "增加组件类别", this);
    //connect(pAddComponentGroupAction, SIGNAL(triggered()), m_pMainWidget, SIGNAL(sigAddGroup()));

    QAction *pImportComponentAction = new QAction(QIcon(":/images/toolbar/importcomponent.png"), "导入自定义组件", this);
    connect(pImportComponentAction, &QAction::triggered, [=]()
    {
        WorkFlowXML::toXML(currentScene->getWorkFlow());
    });

    //添加状态栏提示
    pointerButton->setStatusTip("鼠标正常选择模式");
    linePointerButton->setStatusTip("鼠标连线模式");
    pDeleteItemAction->setStatusTip("删除工作流节点或线");
    pCopyAction->setStatusTip("对选择的内容进行复制操作");
    pPasteAction->setStatusTip("对复制的内容进行粘贴操作");
    pCreateWFlowAction->setStatusTip("创建一个新的工作流");
    pCheckAction->setStatusTip("校验当前工作区内的工作流");
    pExecAction->setStatusTip("执行工作区内的工作流");
    pViewResultAction->setStatusTip("查看工作流执行结果");
    pAddComponentGroupAction->setStatusTip("新添加一个组件类别");
    pImportComponentAction->setStatusTip("导入用户自定义组件");

    //把动作添加到工具栏，QAction就会自动变成工具
    pToolBar->addWidget(pointerButton);
    pToolBar->addWidget(linePointerButton);
    pToolBar->addAction(pDeleteItemAction);
    pToolBar->addAction(pCopyAction);
    pToolBar->addAction(pPasteAction);
    pToolBar->addAction(pCreateWFlowAction);
    pToolBar->addAction(pCheckAction);
    pToolBar->addAction(pExecAction);
    pToolBar->addAction(pViewResultAction);
    pToolBar->addAction(pAddComponentGroupAction);
    pToolBar->addAction(pImportComponentAction);
}

void MainWindow::initStatusBar()
{
    //状态栏
    QStatusBar *pStatusBar = new QStatusBar(this);
    QLabel *pLabelTxt = new QLabel("Made by: 中国空气动力研究院; Version: 1.0", pStatusBar);
    QPalette pe;
    pe.setColor(QPalette::WindowText, Qt::darkGreen);
    pLabelTxt->setPalette(pe);
    pStatusBar->addPermanentWidget(pLabelTxt);

    this->setStatusBar(pStatusBar);
}

void MainWindow::initMenuBar()
{
    //菜单栏
    QMenuBar *pMenuBar = new QMenuBar(this);
    this->setMenuBar(pMenuBar);

    //创建菜单
    QMenu *pFileMenu = new QMenu("文件(&F)", pMenuBar);
    QMenu *pEditMenu = new QMenu("编辑(&E)", pMenuBar);
    QMenu *pHelpMenu = new QMenu("帮助(&H)", pMenuBar);

    //创建菜单动作
    QAction *pNewAction = new QAction("新建(&N)", this);
    QAction *pOpenAction = new QAction("打开(&O)", this);
    QAction *pSaveAction = new QAction("保存(&S)", this);

    //添加状态栏提示
    pNewAction->setStatusTip("新建一个文件或项目");
    pOpenAction->setStatusTip("打开一个文件或项目");
    pSaveAction->setStatusTip("保存");

    //添加动作到新建菜单，QAction就会自动变成子菜单
    pFileMenu->addAction(pNewAction);
    pFileMenu->addAction(pOpenAction);
    pFileMenu->addSeparator();
    pFileMenu->addAction(pSaveAction);

    //给编辑菜单添加子菜单
    pEditMenu->addAction("剪切(&T)");

    //给帮助菜单添加子菜单
    pHelpMenu->addAction("关于(&A)");

    //把菜单添加到菜单栏
    pMenuBar->addMenu(pFileMenu);
    pMenuBar->addMenu(pEditMenu);
    pMenuBar->addMenu(pHelpMenu);


    connect(pNewAction, &QAction::triggered, this, &MainWindow::createWorkFlowTriggered);
    connect(pOpenAction, &QAction::triggered, this, &MainWindow::openWorkFlowTriggered);

}

void MainWindow::createWorkFlowTriggered()
{
    int index =0;
    for(int i=0;i<ui->widLeft->getFlowModel()->rowCount();i++)
    {
        QString text = ui->widLeft->getFlowModel()->item(i)->text();
        if(text.startsWith("新建工作流"))
        {
            qDebug()<<text.mid(QString("新建工作流").size());
            int temp = text.mid(QString("新建工作流").size()).toInt();
            if(temp>index)
            {
                index = temp;
            }
        }
    }
    index++;
    QString workFlowName = QString("新建工作流%1").arg(index);
    DiagramScene *scene = new DiagramScene;

    WorkFlowProperty*property = new WorkFlowProperty{workFlowName,workFlowName,"WFStandardMode"};
    WorkFlow* workFlow = new WorkFlow(property);
    WorkFlowParam* Param = new WorkFlowParam{"xxx",QDateTime::currentDateTime(),"xxx"};
    workFlow->setParam(Param);
    scene->setWorkFlow(workFlow);

    contreView->setScene(scene);
    currentScene = scene;


    QStandardItem *item = new QStandardItem(workFlowName);
    item->setData(QVariant::fromValue(scene),Qt::UserRole+1);
    ui->widLeft->getFlowModel()->appendRow(item);

}

void MainWindow::pointerGroupClicked(int id)
{
    Mode tmpmodel = Mode(id);
    Single::install().setMode(tmpmodel);
}

void MainWindow::delectStepTriggered()
{
    QList<QGraphicsItem *> selectedItems = currentScene->selectedItems();
    if(!selectedItems.isEmpty())
    {
        StepBase* step = dynamic_cast<StepBase*>( selectedItems.first());
        if(step!=nullptr)
        {
            std::list<CPort*> listCPort;
            step->getCstep()->getListPort(listCPort);

            for(auto item:listCPort)
            {
                currentScene->getWorkFlow()->removeCRelationContainCPort(item);
            }
            currentScene->getWorkFlow()->deleteStep(step->getCstep());
            return ;
        }
        Relation* relation = dynamic_cast<Relation*>( selectedItems.first());
        if(relation!=nullptr)
        {
            currentScene->getWorkFlow()->removeCRelationAndCLink(relation->getCrelation());
        }

    }

}

void MainWindow::openWorkFlowTriggered()
{
    QString xmlFile = QFileDialog::getOpenFileName(this,tr("开打工作流"),QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation)
                                                    ,"XML (*.xml);;All (*.*)");
    if(xmlFile.isEmpty())
    {
        qDebug()<<" getOpenFileName error";
        return ;
    }

   WorkFlow* workFlow = WorkFlowXML::toWorkFlow(xmlFile);
   DiagramScene *scene = new DiagramScene();
   scene->setWorkFlow(workFlow);
   scene->openWorkFlow(workFlow);
   currentScene = scene;

   QStandardItem *item = new QStandardItem(workFlow->getProperty()->name);
   item->setData(QVariant::fromValue(scene),Qt::UserRole+1);
   ui->widLeft->getFlowModel()->appendRow(item);





}


